import md5 from 'js-md5';
import Cryptojs from 'crypto-js'

export default {
  whatsapp_share(url, name) {
    // const curHref = window.location.href;
    // content是自己定义的一些需要分享的内容;
    let content = name;

    content += '\n' + url;
    if (localStorage.getItem('ismobile')==2) {
      Toast({
        message: 'Please operate on your mobile phone',
        duration: 1500
      });
    } else {
      // 调起 WhatsApp,自己选择联系人进行内容分享
      let shareLink = 'whatsapp://send?text=' + encodeURIComponent(content);
      // 调起 WhatsApp 给指定手机号发消息
      // let toSomeoneLink = 'whatsapp://send?phone=' + url + '&text='+ encodeURIComponent(content);
      window.location.href = shareLink;
      // 如果用户没有安装APP，则提示用户去安装APP
      // setTimeout(() => {
      //   window.location.href = 'https://www.whatsapp.com/';
      // }, 2000);
    }
  },

  /*
       订单状态
            PENDING_PAYMENT 等待付款
            PENDING_REVIEW 等待审核
            PENDING_SHIPMENT 等待发货
            SHIPPED 已发货
            RECEIVED 已收货
            COMPLETED 已完成
            FAILED 已失败
            CANCELED 已取消
            DENIED 已拒绝,
     */
  orderStatus: function(status) {
    var resText = "";
    if ("PENDING_PAYMENT" == status) {
      resText = "order.PENDING_PAYMENT";
    } else if ("PENDING_REVIEW" == status) {
      resText = "order.PENDING_REVIEW";
    } else if ("PENDING_SHIPMENT" == status) {
      resText = "order.PENDING_SHIPMENT";
    } else if ("SHIPPED" == status) {
      resText = "order.SHIPPED";
    } else if ("RECEIVED" == status) {
      resText = "order.RECEIVED";
    } else if ("COMPLETED" == status) {
      resText = "order.COMPLETED";
    } else if ("FAILED" == status) {
      resText = "order.FAILED";
    } else if ("CANCELED" == status) {
      resText = "order.CANCELED";
    } else if ("DENIED" == status) {
      resText = "order.DENIED";
    }
    return resText;
  },
  orderStatusTip: function(status, deliveryTime) {
    var resText = "";
    if ("PENDING_PAYMENT" == status) {
      resText = "order.PENDING_PAYMENT_TIP";
    } else if ("PENDING_REVIEW" == status) {
      resText = "order.PENDING_REVIEW_TIP";
    } else if ("PENDING_SHIPMENT" == status) {
      if(parseInt(deliveryTime) > 48){
        resText = "order.PENDING_SHIPMENT_TIP_day";
      } else {
        resText = "order.PENDING_SHIPMENT_TIP";
      }

    } else if ("SHIPPED" == status) {
      resText = "order.SHIPPED_TIP";
    } else if ("RECEIVED" == status) {
      resText = "order.RECEIVED_TIP";
    } else if ("COMPLETED" == status) {
      resText = "order.COMPLETED_TIP";
    } else if ("FAILED" == status) {
      resText = "order.FAILED_TIP";
    } else if ("CANCELED" == status) {
      resText = "order.CANCELED_TIP";
    } else if ("DENIED" == status) {
      resText = "order.DENIED_TIP";
    }
    return resText;
  },
  /*
       订单状态
            PENDING_PAYMENT 等待付款
            PENDING_REVIEW 等待审核
            PENDING_SHIPMENT 等待发货
            SHIPPED 已发货
            RECEIVED 已收货
            COMPLETED 已完成
            FAILED 已失败
            CANCELED 已取消
            DENIED 已拒绝,
     */
  orderStatusByCode: function(stCode) {
    var resText = "";
    switch (stCode) {
      case 0:
        resText = "order.PENDING_PAYMENT";
        break;
      case 1:
        resText = "order.PENDING_REVIEW";
        break;
      case 2:
        resText = "order.SHIPPED";
        break;
      case 3:
        resText = "order.RECEIVED";
        break;
      case 4:
        resText = "order.COMPLETED";
        break;
      case 5:
        resText = "order.FAILED";
        break;
      case 6:
        resText = "order.CANCELED";
        break;
      case 7:
        resText = "order.DENIED";
        break;
      default:
    }
    return resText;
  },
  toRateNumber(amount, rate) {
    return (parseFloat(amount) * parseFloat(rate)).toFixed(2);
  },
  GetGeetestLang(){
    let lang = '';
    let locale = localStorage.getItem("language") || "zh";
    if('jp' == locale){
      lang = 'ja';
    } else if('en' == locale){
      lang = 'en';
    }  else if('zh' == locale){
      lang = 'zh-cn';
    }  else if('vi_VN' == locale){
      lang = 'vi';
    } else if('in_ID' == locale){
      lang = 'in_ID';
    }  else {
      lang = 'en';
    }
    return lang;
  },
  getCountDown(expire) {
    let timestamp = new Date().getTime();
    let expireTimestam = new Date(expire).getTime();
    let countDown = expireTimestam - timestamp;
    return countDown;
  },
  floatAdd(a, b, ifixed) {
    let f1 = parseFloat(a);
    let f2 = parseFloat(b);
    return (f1 + f2).toFixed(ifixed);
  },
  createDeviceId(){
    let timestamp = new Date().getTime();
    return md5(timestamp.toString()).substring(0,15);
    // return 'xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/[xy]/g, function(c) {
    //   var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    //   return v.toString(16);
    // });
  },

  checkPasslevel(value, minLength){
    var lv = 0;
    if(value.length < minLength){//最初级别
      return lv;
    }
    if(/\d/.test(value)){//如果用户输入的密码 包含了数字
      lv++;
    }
    if(/[a-z]/.test(value)){//如果用户输入的密码 包含了小写的a到z
      lv++;
    }
    if(/[A-Z]/.test(value)){//如果用户输入的密码 包含了大写的A到Z
      lv++;
    }
    if(/\W/.test(value)){//如果是非数字 字母 下划线
      lv++;
    }
    return lv;
  },
  isValid(a) {
    if (null == a) {
      return false;
    }
    if (undefined == typeof a) {
      return false;
    }
    return true;
  },

  GetRandomNum(min, max){
    var range = max - min;
    var rand = Math.random();
    return (min + Math.round(rand*range));
  },

  validCheckRes(res) {
    if (!this.isValid(res)) {
      return false;
    }
    if (!this.isValid(res.data)) {
      return false;
    }
    return true;
  },
  isArray(o) {
    return Object.prototype.toString.call(o) == "[object Array]";
  },
  getPlatform() {
    let p = navigator.platform;
    let u = navigator.userAgent;
    let is_android = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1;
    let is_ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    if (
      p == "Win32" ||
      p == "Win64" ||
      p == "MacPPC" ||
      p == "MacIntel" ||
      p == "X11" ||
      p == "Linux i686"
    ) {
      //PC调试环境
      return "PC";
    } else {
      if (is_android) {
        //Android终端
        return "ANDROID";
      } else if (is_ios) {
        //IOS终端
        return "IOS";
      }
    }
  },
  // 回调给app端的消息
  callBackApp( jsonData ){
    let os = this.getPlatform();
    if("ANDROID" == os){
      window.Android.callApp(JSON.stringify(jsonData));
    } else if ("IOS" == os) {
      //调用oc方法
      window.webkit.messageHandlers.callApp.postMessage(JSON.stringify(jsonData));
    }
  },
  updateVerifyBusinessAssetStatus(vlue){
    sessionStorage.setItem("verifyBusinessAssetStatus", vlue);
  },

  isVerifyBusinessAsset(){
    var bReturn = false;
    let status = sessionStorage.getItem("verifyBusinessAssetStatus");
    if("true" == status){
      bReturn = true;
    }
    return bReturn;
  },

  updateVerifyStatus(vlue){
    sessionStorage.setItem("verifyStatus", vlue);
  },
  isVerify(){
    var bReturn = false;
    let status = sessionStorage.getItem("verifyStatus");
    if("true" == status){
      bReturn = true;
    }
    return bReturn;
  },
  sign(obj){
    let apiSecret = 'test'
    var keys=[];
    for(let key in obj){
      keys.push(key);
    }

    keys.sort();
    let strTemp = '';
    for(let k in keys){
      let value = obj[keys[k]];
      if('string' != typeof value){
        value = JSON.stringify(value);
      }
      strTemp += keys[k] + '=' + value + '&';
    }
    strTemp=strTemp.replace(/&$/,""); //去掉最后的逗号

    return Cryptojs.HmacSHA256(strTemp, apiSecret).toString();
  },

  formatDecimal(num, decimal) {
    num = num.toString()
    let index = num.indexOf('.')
    if (index !== -1) {
      num = num.substring(0, decimal + index + 1)
    } else {
      num = num.substring(0)
    }
    return parseFloat(num).toFixed(decimal)
  },
  /**
   * 精确计算两数的和
   * @method additive
   * @param {Number} v1 有效数值1
   * @param {Number} v2 有效数值2
   * @return {Number} 两数值的和
   */
  additive(v1,v2){
    var n1,n2,m;
    //获取两数的浮点位数
    try{n1=v1.toString().split(".")[1].length;}catch(e){n1=0}
    try{n2=v2.toString().split(".")[1].length;}catch(e){n2=0}
    //获取10为底数，最大两位数值的浮点位数次幂
    m=Math.pow(10,Math.max(n1,n2));
    return (v1*m+v2*m)/m;
  },

  /**
   * 精确计算两数的差
   * @method subtraction
   * @param {Number} v1 有效数值1
   * @param {Number} v2 有效数值2
   * @return {Number} v1-v2两数值的差
   */
  subtraction(v1,v2){
    var n1,n2,m,n;
    //获取两数的浮点位数
    try{n1=v1.toString().split(".")[1].length}catch(e){n1=0}
    try{n2=v2.toString().split(".")[1].length}catch(e){n2=0}
    //获取10为底数，数值的最大浮点位数次幂
    m=Math.pow(10,Math.max(n1,n2));
    //获取数值的最大浮点位数，设置为返回值的精度长度
    n=Math.max(n1,n2);
    //toFixed格式化数值位数
    return ((v1*m-v2*m)/m).toFixed(n);
  },
  /**
   * 精确计算两数的商
   * @method division
   * @param {Number} v1 有效数值1  被除数
   * @param {Number} v2 有效数值2  除数
   * @return {Number} 两数值的商
   */
  division(v1,v2){
    var t1=0,t2=0,n1,n2;
    var s1=v1.toString();
    var s2=v2.toString();
    //获取两数的浮点位数
    try{t1=s1.split(".")[1].length}catch(e){}
    try{t2=s2.split(".")[1].length}catch(e){}
    //去除小数点符号，获取整数
    n1=Number(s1.replace(".",""))
    n2=Number(s2.replace(".",""))
    //两整数相除，乘以10为底数的（除数浮点位数-被除数的浮点位数）
    return (n1/n2)*pow(10,t2-t1);
  },
  /**
   * 精确计算两数的积
   * @method subtraction
   * @param {Number} v1 有效数值1
   * @param {Number} v2 有效数值2
   * @return {Number} 两数值的乘积
   */
  multiplication(v1,v2) {
    var m=0;
    let s1=v1.toString();
    let s2=v2.toString();
    //获取两数的浮点位数
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    //去除小数点的两数相乘，除以（10为底数，两值浮点位数的次幂）
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
  },


};

String.prototype.format = function(args) {
  var result = this;
  if (arguments.length > 0) {
    if (arguments.length == 1 && typeof (args) == "object") {
      for (var key in args) {
        if (args[key] != undefined) {
          var reg = new RegExp("({" + key + "})", "g");
          result = result.replace(reg, args[key]);
        }
      }
    }
    else {
      for (var i = 0; i < arguments.length; i++) {
        if (arguments[i] != undefined) {
          //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
          var reg = new RegExp("({)" + i + "(})", "g");
          result = result.replace(reg, arguments[i]);
        }
      }
    }
  }
  return result;
}
String.format = function () {
  if (arguments.length == 0)
    return null;

  var str = arguments[0];
  for (var i = 1; i < arguments.length; i++) {
    var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
    str = str.replace(re, arguments[i]);
  }
  return str;
}
